<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    :close-on-click-modal="false"
    @close="closeDialog"
    @open="dialogOpen"
  >
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="roleIds" v-loading="loading">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="confirmAddRole">确定</el-button>
      <el-button size="small" @click="closeDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleListApi } from '@/api/settings'
import { getUserInfoApi } from '@/api/user'
import { assignRolesApi } from '@/api/employees'

export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      roleIds: [], // 存放选择的角色复选框
      roleList: [], // 存放获取来的所有角色
      loading: false
    }
  },
  methods: {
    /**
     * 关闭弹框
     */
    closeDialog() {
      this.$emit('update:showRoleDialog', false)
    },
    /**
     * 获取所有的角色列表
     */
    async getRoleList() {
      const { data: { rows }} = await getRoleListApi(1, 9999)
      this.roleList = rows
    },
    /**
     * 获取原本用户信息  用来回显数据
     */
    async getUserInfo() {
      const { data } = await getUserInfoApi(this.userId)
      //   console.log(data)
      this.roleIds = data.roleIds
    },
    /**
     * 打开弹框的时候调用上面俩个方法
     */
    dialogOpen() {
      // 添加加载状态  提升显示
      this.loading = true
      //   this.getRoleList()
      //   this.getUserInfo()
      //   等待这两个获取信息的接口 全部执行完毕之后 在结束加载
      Promise.all([this.getRoleList(), this.getUserInfo()])
        .then(() => {
          this.loading = false
        })
    },
    /**
     * 点击确认  修改角色
     */
    async confirmAddRole() {
      await assignRolesApi({ id: this.userId, roleIds: this.roleIds })
      this.$message.success('员工角色分配成功')
      this.closeDialog()
    }
  }
}
</script>

<style lang="scss" scoped>
.assign-role {
  ::v-deep {
    .el-checkbox {
      font-size: 30px;
    }
  }
}
</style>
